#include <bits/stdc++.h>
using namespace std;
const int N = 2e4 + 10;
int dfn[N], low[N], deg[N], sz[N], scc[N], outdeg[N], indeg[N], dfncnt, scccnt;
bool instk[N];
vector<int> adj[N];
stack<int> s;
int n, m;
void tarjan(int u) {
  dfn[u] = low[u] = ++dfncnt;
  s.push(u);
  instk[u] = true;
  for (auto v : adj[u]) {
    if (!dfn[v]) {
      tarjan(v);
      low[u] = min(low[u], low[v]);
    } else if (instk[v]) {
      low[u] = min(low[u], dfn[v]);
    }
  }
  if (dfn[u] == low[u]) {
    scccnt++;
    int k = -1;
    do {
      k = s.top();
      s.pop();
      sz[scccnt]++;
      instk[k] = false;
      scc[k] = scccnt;
    } while (k != u);
  }
}
int main() {
  int tc;
  cin >> tc;
  while (tc--) {
    cin >> n >> m;
    for (int *arr : {dfn, low, deg, sz, scc, outdeg, indeg})
      memset(arr, 0, sizeof dfn);
    memset(instk, 0, sizeof instk);
    while (s.size()) s.pop();
    dfncnt = scccnt = 0;
    for (int i = 1; i <= n; ++i) adj[i].clear();
    for (int i = 1; i <= m; ++i) {
      int u, v;
      cin >> u >> v;
      adj[u].push_back(v);
    }
    for (int i = 1; i <= n; ++i)
      if (!dfn[i]) tarjan(i);

    for (int u = 1; u <= n; ++u)
      for (int v : adj[u])
        if (scc[u] != scc[v]) ++outdeg[scc[u]], ++indeg[scc[v]];

    if (scccnt == 1) {
      cout << 0 << endl;
    } else {
      int cntin = 0, cntout = 0;
      for (int i = 1; i <= scccnt; ++i) {
        if (!indeg[i]) ++cntin;
        if (!outdeg[i]) ++cntout;
      }
      cout << max(cntin, cntout) << endl;
    }
  }
}
